﻿
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using cadDatabase = Autodesk.AutoCAD.DatabaseServices.Database;
using cadTransM = Autodesk.AutoCAD.DatabaseServices.TransactionManager;
using cadTran = Autodesk.AutoCAD.DatabaseServices.Transaction;
using cadService = Autodesk.AutoCAD.DatabaseServices;
using JsonYNCNumsys.entity;

namespace JsonYNCNumsys
{
    /// <summary>
    /// 操作CAD的实体类，主要实现
    /// （1）标题栏的读取（更新到数据库）（2）填写到标题栏。
    /// </summary>
    public class CadHelperDal
    {
        [DllImport("kernel32.dll")]
        private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr hObject);

        private const int OF_READWRITE = 2;
        private const int OF_SHARE_DENY_NONE = 0x40;
        private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
        public static int FileIsOpen(string fileFullName)
        {
            if (!File.Exists(fileFullName))
            {
                return -1;
            }
            IntPtr handle = _lopen(fileFullName, OF_READWRITE | OF_SHARE_DENY_NONE);
            if (handle == HFILE_ERROR)
            {
                return 1;
            }
            CloseHandle(handle);
            return 0;
        }
        public static void FilesCopyNew(string sPath,string sPathNew)
        {
            
        }

        public static void FilesCopyNewAndDelete(DataTable dt, string folder, bool bak)
        {
            string bakFoder = Path.Combine(folder, "bak" + DateTime.Now.ToString("yyyyMMddHHmmss"));
            if (bak)
            {
                if (!Directory.Exists(bakFoder))
                {
                    Directory.CreateDirectory(bakFoder);
                }
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string xh = dt.Rows[i]["图纸编号"].ToString();
                xh = xh.PadLeft(6, '0');
                string oldName = (string)dt.Rows[i]["图纸类型"] + "-" + (string)dt.Rows[i]["零件序号"] + ".dwg";
                string newName = (string)dt.Rows[i]["图纸类型"] + xh + "-" + (string)dt.Rows[i]["零件序号"] + ".dwg";
                string fullOldName = Path.Combine(folder, oldName);
                if (File.Exists(fullOldName))
                {
                    string fullNewName = Path.Combine(folder, newName);
                    if (!File.Exists(fullNewName))
                    {
                        File.Copy(fullOldName, fullNewName);
                        if (bak)
                        {
                            if (Directory.Exists(bakFoder))
                            {
                                string bakName = Path.Combine(bakFoder, oldName);
                                //File.Copy(fullOldName, bakName);
                            }
                        }
                        File.Delete(fullOldName);
                    }
                }
            }
        }
        /// <summary>
        /// 当前文件路径
        /// </summary>
        /// <param name="folderPath">文件路径。</param>
        /// <param name="dtrow">多条图纸号结果</param>
        public static void SetTitle(string filePath, DataRow dr)
        {
            try
            {
                string cadPaperCode = (string)dr["零件序号"];
                string paperCode = dr["图纸编号"].ToString();
                string s用户名 = dr["申请人"].ToString();
                string s审核人 = dr["审核人"].ToString();
                string s日期 = dr["申请日期"].ToString();
                string s机床型号 = dr["机床型号"].ToString();
                //if (cadPaperCode != @"ZP-4C")
                {
                    string s1 = (string)dr["图纸类型"];
                    string s2 = dr["图纸编号"].ToString().Replace(s1, "");
                    string s3 = dr["零件序号"].ToString();
                    cadDatabase sourceDb = new cadDatabase(false, true);
                    if (File.Exists(filePath))
                    {//文件存在
                        //sourceDb.ReadDwgFile(filePath, System.IO.FileShare.ReadWrite, true, "");
                        sourceDb.ReadDwgFile(filePath, System.IO.FileShare.Read, false, "");
                        
                        cadTransM tm = sourceDb.TransactionManager;
                        using (cadTran cadTran = tm.StartTransaction())
                        {
                            cadService.BlockTable bt = (cadService.BlockTable)tm.GetObject(sourceDb.BlockTableId, cadService.OpenMode.ForWrite, false);
                            foreach (cadService.ObjectId btrId in bt)
                            {
                                cadService.BlockTableRecord btr = (cadService.BlockTableRecord)tm.GetObject(btrId, cadService.OpenMode.ForWrite, false);
                                string s图纸大小 = "A" + dr["图纸类型"].ToString().Substring(0, 1);
                                if (btr.Name == s图纸大小 || btr.Name == (s图纸大小 + @"图框"))//新版本的块名有变化
                                {
                                    cadService.ObjectIdCollection btrObjIds = new cadService.ObjectIdCollection();
                                    btrObjIds = btr.GetBlockReferenceIds(true, true);
                                    foreach (cadService.ObjectId objId in btrObjIds)
                                    {
                                        string sDate = dr["申请日期"] != null ? ((DateTime)dr["申请日期"]).ToString("yy.MM.dd") : "";
                                        cadService.BlockReference blkRef = (cadService.BlockReference)cadTran.GetObject(objId, cadService.OpenMode.ForWrite);
                                        List<BlockAttributeEntity> lstBlRefAttr = new List<BlockAttributeEntity>();
                                        lstBlRefAttr.Add(new BlockAttributeEntity("零部件图号", s1 + dr["图纸编号"].ToString().PadLeft(6, '0')));
                                        lstBlRefAttr.Add(new BlockAttributeEntity("零部件图号_1", s1 + dr["图纸编号"].ToString().PadLeft(6, '0')));
                                        lstBlRefAttr.Add(new BlockAttributeEntity("机床型号", dr["机床型号"].ToString()));
                                        lstBlRefAttr.Add(new BlockAttributeEntity("设计者", dr["申请人"].ToString()));
                                        lstBlRefAttr.Add(new BlockAttributeEntity("设计日期", sDate));
                                        lstBlRefAttr.Add(new BlockAttributeEntity("审核者", dr["审核人"].ToString()));
                                        lstBlRefAttr.Add(new BlockAttributeEntity("审核日期", sDate));
                                        SetTitleDal setAttr = new SetTitleDal(sourceDb, cadTran, blkRef, lstBlRefAttr);
                                        setAttr.Do();
                                        //TitleAttributeGetDal getAttr = new TitleAttributeGetDal(sourceDb, cadTran, blkRef);
                                        //getAttr.Do();
                                        lstBlRefAttr.Clear();
                                        //lstBlRefAttr = getAttr.LstAttr;
                                        bool findLbj = false;//零部件对应[名称]
                                        bool findCL = false;//材料[规格]
                                        int iCode = (int)dr["图纸编号"];//[图纸编号]
                                        string sLbj = string.Empty;
                                        string sCl = string.Empty;
                                        foreach (BlockAttributeEntity bae in lstBlRefAttr)
                                        {
                                            if (bae.Tag == @"零部件名称")
                                            {
                                                sLbj = bae.TextString;
                                                findLbj = true;
                                            }
                                            else if (bae.Tag == @"材料")
                                            {
                                                sCl = bae.TextString;
                                                findCL = true;
                                            }
                                            else
                                            {

                                            }
                                            if (findLbj && findCL)
                                            {
                                                //更新数据库
                                                //PaperCodeDal papercodedal = new PaperCodeDal();
                                                //papercodedal.UpdatePapercode(iCode, sLbj, sCl);
                                                //更新表 ,dtPaperCodeResult
                                                dr["名称"] = sLbj;
                                                dr["规格"] = sCl;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            cadTran.Commit();
                            cadTran.Dispose();
                        }
                        sourceDb.SaveAs(filePath, cadService.DwgVersion.AC1015);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
            }
        }
    }
}
